using UnityEngine;
using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;

public class CaseSelectionScreen : MonoBehaviour {

	public GUIStyle blankStyle;
	public Texture logo;
	string message;
	public int caseSet;
	public string mode;
	bool training;
	
	struct Case
	{
		public int id;
		public string title;
		public string description;
	}
	
	List<Case> cases = new List<Case>();
	MySqlDataReader reader;
	MySqlConnection connection;
	MySqlCommand command;
	string query;
	int selectedCase = -1;
    string[] selectableCases;
	

	// Use this for initialization
	void Start () {
		message = "";
			
		if(User.CaseMode == "NONE"){
			message = "There are no cases for you to select";
			return;
		}
		else if(User.CaseMode == "TRAINING"){
			training = true;
		}
		else{
			training = false;
		}
		
		try
        {
			connection = new MySqlConnection(Configuration.MySQLConnectionString);
            connection.Open();
			
			using (connection)
			{
				
				query = "SELECT c.case_id, c.title, c.description FROM VP_OFP.casesetmap csm, VP_OFP.case c WHERE csm.Caseset_case_set_id='" + User.CaseSetID + "' AND c.training=" + training;
				command = new MySqlCommand(query, connection);
				
		        reader = command.ExecuteReader();
	            
				while(reader.Read())
	            {
					Case cas = new Case();
					cas.id = (int)reader["case_id"];
					cas.title =  reader["title"].ToString();
					cas.description = reader["description"].ToString();
					cases.Add(cas);
				}
			}
			
		}
		catch(Exception ex){
			message = ex.ToString();
			return;
		}
		selectableCases = new string[cases.Count];
		for(int i=0; i<cases.Count; i++){
			selectableCases[i] = cases[i].title;
		}
	}

    void OnGUI()
    {
		int width = Screen.width / 2;
		int height = Screen.height / 2;
		GUI.Button(new Rect(0, 50, 160, 45), logo, blankStyle);
		GUI.depth = 0;
		GUI.Label(new Rect(0, 250, 160, 45), message);
		selectedCase = GUI.SelectionGrid(new Rect(width - 300,height - 25, 600, 50), selectedCase, selectableCases, 4);
		if(selectedCase != -1)
		{
			GUI.Label(new Rect(width, height + 300, 160, 45), cases[selectedCase].description);
			if (GUI.Button(new Rect(width + 227, height - 181, 110, 40), "Select")  || (Event.current.keyCode == KeyCode.Return))
            {
				User.SelectedCase = cases[selectedCase].id;
				Application.LoadLevel(2);
            }
		}
    }
	
    
}
